<template>
  <a-modal
    :width="600"
    :visible="open"
    :title="formTitle"
    @cancel="cancel"
  >
    <a-form enctype="multipart/form-data">
      <a-upload :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
        <a-button> <a-icon type="upload" /> 选择文件 </a-button>
      </a-upload>
    </a-form>
    <template slot="footer">
      <a-button :disabled="disabled" @click="cancel">
        取消
      </a-button>
      <a-button type="primary" :disabled="disabled" @click="submitForm(true)">
        上传
      </a-button>
    </template>
  </a-modal>
</template>
<script>
import { upload } from '@/api/dockerinsight/fileSystem'
export default {
  name: 'UploadForm',
  components: {
  },
  props: {
    currentPath: {
      type: String,
      required: true
    },
    ip: {
      type: String,
      required: true
    }
  },
  data () {
    return {
      open: false,
      formTitle: undefined,
      disabled: false,
      form: {},
      fileList: [],
      uploading: false
    }
  },
  created () {
  },
  methods: {
    // 上传
    handleUpload () {
      this.reset()
      this.open = true
      this.formTitle = '在当前目录下上传文件'
    },
    // 重置表单
    reset() {
      this.fileList = []
    },
    // 取消按钮
    cancel () {
      this.open = false
      this.reset()
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      const size = file.size / 1024 / 1024
      if (size > 200) {
        this.$message.warning('文件大小不能超过200M')
        return false
      }
      this.fileList = [file]
      if (this.fileList.length > 1) {
        this.$message.info('只能选择一个文件！')
      }
      return false
    },
    submitForm(disabled) {
      this.disabled = disabled
      const { fileList } = this
      const formData = new FormData()
      fileList.forEach(file => {
        formData.append('file', file)
      })
      this.uploading = true
      formData.append('ip', this.ip)
      formData.append('currentPath', this.currentPath)
      console.log(formData)
      upload(formData).then(response => {
        this.disabled = false
        this.open = false
        this.$emit('ok')
        this.$emit('close')
      }).catch(error => {
        console.log(error)
        this.disabled = false
      })
    }
  }
}
</script>
